package com.Policing.util;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.Toast;

/**
 * @作者(author): WR
 * @创建时间(date): 2020/6/6
 */
        /*  使用方法
        NetworkReceiver receiver=new NetworkReceiver();
        IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);//网络状态
        registerReceiver(receiver,intentFilter);*/

public class NetworkReceiver extends BroadcastReceiver {
    private request request;

    public NetworkReceiver(NetworkReceiver.request request) {
        this.request = request;
    }

    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            //说明当前有网络
            if (networkInfo != null && networkInfo.isAvailable()) {
                request.requestResult(true);
                Toast.makeText(context, "网络已经连接", Toast.LENGTH_SHORT).show();
              /*  int type = networkInfo.getType();
                switch (type) {
                    case ConnectivityManager.TYPE_MOBILE:
                        Toast.makeText(context, "当前移动网络正常", Toast.LENGTH_SHORT).show();
                        break;
                    case ConnectivityManager.TYPE_WIFI:
                        Toast.makeText(context, "当前WIFI网络正常", Toast.LENGTH_SHORT).show();
                        break;
                    case ConnectivityManager.TYPE_ETHERNET:
                        Toast.makeText(context, "当前以太网网络正常", Toast.LENGTH_SHORT).show();
                        break;
                }*/
            } else {
                //说明当前没有网络
                request.requestResult(false);
                Toast.makeText(context, "当前网络异常", Toast.LENGTH_SHORT).show();
            }
        }
    }
    public interface request {
        void requestResult(boolean result);
    }

}
